import os
import datetime
import allure
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from utils.log_util import logger


def wait_element(driver, by, value, timeout=10):
    """
    显式等待-单个元素
    """
    try:
        return WebDriverWait(driver, timeout).until(
            # 等待元素出现在页面DOM中
            EC.visibility_of_element_located((by, value))
        )
    except TimeoutError:
        logger.info(f"元素{value}未找到")
        return None


def wait_elements(driver, by, value, timeout=10):
    """
    显式等待-多个元素
    """
    try:
        return WebDriverWait(driver, timeout).until(
            # 等待页面中所有匹配的元素变得可见
            EC.visibility_of_all_elements_located((by, value))
        )
    except TimeoutError:
        logger.info(f"元素{value}未找到")
        return None


def input_text(driver, by, value, text):
    """
    输入文本到输入框
    """
    element = wait_element(driver, by, value)
    element.clear()
    element.send_keys(text)


def click_button(driver, by, value):
    """
    点击按钮
    """
    element = wait_element(driver, by, value)
    element.click()


def get_element_text(driver, by, value):
    """
    获取元素文本
    """
    element = wait_element(driver, by, value)
    return element.text


root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def screenshot(driver):
    """
    屏幕截图并保存到allure报告
    """
    img_path = os.path.join(root_path, 'images',
                            f'{datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")}.png')
    # driver.get_screenshot_as_file(img_path)
    allure.attach(driver.get_screenshot_as_png(), '页面截图')
